package com.example.za.account.activity;


import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.example.za.account.R;
import com.example.za.account.dao.ExpenseCatDao;
import com.example.za.account.dao.IncomeCatDao;
import com.example.za.account.dao.UserDao;
import com.example.za.account.model.User;
import com.example.za.account.utils.L;
import com.example.za.account.utils.MD5Encrypt;
import com.example.za.account.utils.NetUtils;
import com.example.za.account.utils.T;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.SaveListener;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_login_username)
    EditText mEtLoginName;
    @BindView(R.id.et_login_pass)
    EditText mEtLoginPass;
    private boolean isStartMainActivity = false;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

    }

    @OnClick({R.id.btn_login, R.id.label_register, R.id.label_forget})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login: {
                if (!NetUtils.isConnected(this)) {
                    T.showShort(this, getString(R.string.check_net_connect));
                    return;
                }
                String name = mEtLoginName.getText().toString().trim();
                final String pass = mEtLoginPass.getText().toString().trim();
                if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(pass)) {


                    BmobUser.loginByAccount(name, pass, new LogInListener<User>() {

                        @Override
                        public void done(final User user, BmobException e) {
                            if (user != null) {
                                new AsyncTask<Void, Void, Void>() {

                                    @Override
                                    protected Void doInBackground(Void... params) {
                                        UserDao userDao = new UserDao(LoginActivity.this);

                                        String s = user.getSessionToken();
                                        //4a51f0384076514a80a2f293d645cfc5
                                        User curUser = userDao.getCurrentUser(user.getUsername());
                                        if (curUser == null) {
                                            userDao.addUser(new User(user.getUsername(), pass, user.getEmail(), user.getmPicture()));
                                            curUser = userDao.getCurrentUser(user.getUsername());

                                            IncomeCatDao incomeCatDao = new IncomeCatDao(LoginActivity.this);
                                            incomeCatDao.initIncomeCat(curUser);
                                            ExpenseCatDao expenseCatDao = new ExpenseCatDao(LoginActivity.this);
                                            expenseCatDao.initExpensesCat(curUser);

                                        }

                                        if (user.getmPicture() != null) {
                                            L.e("getmPicture:" + user.getmPicture());
                                            File file = new File(getExternalFilesDir(null) + File.separator + BmobUser.getCurrentUser(User.class).getObjectId()
                                                    + File.separator + user.getmPicture());

                                            if (!file.exists()) {
                                                SharedPreferences sharedPreferences = getSharedPreferences("FileUrl", Context.MODE_WORLD_READABLE);
                                                String url = sharedPreferences.getString("url", "");
                                                L.e("获取url" + url);
                                                BmobFile bmobfile = new BmobFile(user.getmPicture(), "", url);
                                                //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
                                                bmobfile.download(file, new DownloadFileListener() {

                                                    @Override
                                                    public void onStart() {
                                                        T.showShort(LoginActivity.this, "开始下载...");
                                                    }

                                                    @Override
                                                    public void done(String savePath, BmobException e) {
                                                        if (e == null) {
                                                            T.showShort(LoginActivity.this, "头像下载成功,保存路径:" + savePath);
                                                        } else {
                                                            L.e("下载失败：" + e.getErrorCode() + "," + e.getMessage());
                                                            T.showShort(LoginActivity.this, "头像下载失败");
                                                        }
                                                    }

                                                    @Override
                                                    public void onProgress(Integer value, long newworkSpeed) {
                                                        L.e("下载进度：" + value + "," + newworkSpeed);
                                                    }

                                                });
                                            }
                                        }

                                        return null;
                                    }

                                    @Override
                                    protected void onPostExecute(Void aVoid) {
                                        if (!isStartMainActivity) {
                                            isStartMainActivity = true;
                                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                            startActivity(intent);
                                            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                                            finish();
                                        }
                                    }
                                }.execute();
                            } else {
                                T.showShort(LoginActivity.this, getString(R.string.error_user_login));
                            }
                        }
                    });
                } else {
                    T.showShort(this, getString(R.string.input_user));
                }
            }
            break;
            case R.id.label_register:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.label_forget:
                startActivity(new Intent(this, ForgetPassActivity.class));
                break;
        }
    }

    @Override
    protected Activity getSubActivity() {
        return this;
    }


}
